<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>客户管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="客户名称">
              <a-input v-model="searchForm.nameLike" />
            </a-form-item>
            <a-form-item label="客户联系人">
              <a-input v-model="searchForm.linkManLike" />
            </a-form-item>
            <a-form-item label="客户类型">
              <a-select v-model="searchForm.isCompany" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="0">个人客户</a-select-option>
                <a-select-option :key="1">企业客户</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="结算类型">
              <a-select v-model="searchForm.settlementType" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
              </a-select>
            </a-form-item>
            <!-- <a-form-item label="所属部门">
                <a-input/>
              </a-form-item>
              <a-form-item label="所属销售">
                <a-select v-model="searchForm.sellerId" class="selectWidth">
                  <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
                </a-select>
            </a-form-item>-->
            <a-form-item label="所属部门">
              <a-tree-select
                class="selectInputWidth"
                v-model="searchForm.deptId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :load-data="onLoadData"
                :tree-data="deptTreeData"
                placeholder="请选择"
                @change="onChangeTree"
              ></a-tree-select>
            </a-form-item>
            <a-form-item label="所属销售">
              <a-select v-model="searchForm.sellerId" class="selectInputWidth">
                <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <!-- 银行卡户名1.1 -->
            <a-form-item label="银行卡户名">
              <a-input v-model="searchForm.accountNameLike" />
            </a-form-item>
            <!-- 1.1.1 -->
            <a-form-item label="是否新客户">
              <a-select v-model="searchForm.isNew" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="1">是</a-select-option>
                <a-select-option :key="0">否</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="创建日期">
              <a-range-picker
                :value="searchForm.startDate ? [searchForm.startDate, searchForm.endDate] : null"
                @change="onDateChange"
              >
                <a-icon slot="suffixIcon" type="calendar" />
              </a-range-picker>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleCreate">+ 创建客户</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出Excel</a-button>
            </a-form-item>
          </a-form>

          <a-table
            :loading="loading"
            :columns="columns"
            :data-source="tableData"
            class="tableMargin"
            :pagination="pagination"
            rowKey="id"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="operation" slot-scope="text, record">
              <a @click="editIt(record.id)">编辑</a>
              <a @click="viewIt(record.id)">查看</a>
              <a @click="viewCode(record)">客户二维码</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <a-modal v-model="visible" title="货物跟踪码" :width="400" centered :footer="null" destroyOnClose>
      <div ref="imageWrapper" style="overflow:visible !important">
        <div class="main">
          <div class="logo">
            <img src="@@/images/liut_logo.png" alt class="img" />
            <h1>{{orderInfo.custName}}</h1>
          </div>
          <div class="c_code">
            <div id="qrcode" ref="qrcode" class="erw_hwgz"></div>
            <h1>货物跟踪码</h1>
            <p>扫码后查看您的货物运输动态</p>
          </div>
          <div class="c_people">
            <ul>
              <li>
                <img src="@@/images/xs@2x.png" alt />
                <span>客户经理：</span>
                {{orderInfo.seller}}
              </li>
              <li>
                <img src="@@/images/dh@2x.png" alt />
                <span>联系电话：</span>
                {{orderInfo.sellerPhone}}
              </li>
            </ul>
          </div>
        </div>
      </div>
      <a-button block type="primary" @click="downLoadImg">点击下载</a-button>
    </a-modal>
  </div>
</template>

<script>
import { mixin } from '@/common/common'
import html2canvas from 'html2canvas'
import QRCode from 'qrcodejs2'
import { TRUCKINGURL } from '@/common/config'
import { queryCustomerPageList, querySellerDown, queryDeptDown } from '@/api'
import { commonExport } from '@/api/request'

const defaultData = {
  belongCompany: 'JIA_HUA',
  status: 1,
  custTypeLike: 'CUSTOMER',
  sellerId: null,
  deptId: null,
  isSellerQuery: 1
}

const deptData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}

export default {
  mixins: [mixin],
  data () {
    return {
      loading: false,
      sellers: [],
      searchForm: {
        ...defaultData,
        nameLike: '',
        linkManLike: '',
        isCompany: '',
        settlementType: '',
        accountNameLike: '',
        isNew: '', // 是否新客户 1是0否
        startDate: null, // 开始日期
        endDate: null // 结束日期
      },
      columns: [
        {
          title: '序号',
          width: 60,
          scopedSlots: { customRender: 'rn' }
        },
        {
          title: '客户名称',
          ellipsis: true,
          dataIndex: 'name'
        },
        {
          title: '客户类型',
          dataIndex: 'isCompany',
          customRender: (text, row, index) => {
            if (text === 1) {
              return '企业客户'
            } else if (text === 0) {
              return '个人客户'
            }
          },
          _needName: true
        },
        {
          title: '客户联系人',
          dataIndex: 'linkMan1'
        },
        {
          title: '联系电话',
          dataIndex: 'linkManPhone1'
        },
        {
          title: '结算类型',
          dataIndex: 'settlementType',
          customRender: (text, row, index) => {
            return this.checkSettlementTypeName(text)
          },
          _needName: true
        },
        {
          title: '所属销售',
          dataIndex: 'seller'
        },
        {
          title: '是否新客户',
          dataIndex: 'isNewName'
        },
        {
          title: '创建日期',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          width: 180,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      deptTreeData: [],
      isFirstEnd: true,
      // 1.2 客户二维码
      visible: false,
      orderInfo: {}
    }
  },
  methods: {
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      queryCustomerPageList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
        .then(rsp => {
          this.isFirstEnd = false
          this.loading = false
          this.tableData = rsp.data.list
          this.pagination = {
            current: this.pageNum,
            pageSize: rsp.data.pageSize,
            total: rsp.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              this.handleSubmit()
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              this.handleSubmit()
            }
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleCreate () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }
      this.$router.push('/salesCenter/customManageOperation')
    },
    editIt (id) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.$router.push({
        path: '/salesCenter/customManageOperation',
        query: { id }
      })
    },
    viewIt (id) {
      this.$router.push({ path: `customManage/${id}` })
    },
    viewCode (item) {
      this.orderInfo = {
        custName: item.name,
        seller: item.seller,
        sellerPhone: item.sellerPhone
      }
      const _s = this
      setTimeout(() => {
        _s.$nextTick(() => {
          _s.qrcode(item.id)
        })
      }, 200)
      this.visible = true
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      return new Promise((resolve, reject) => {
        queryDeptDown(e).then(rsp => {
          let initData = []
          rsp.data.forEach((value, index) => {
            initData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId
            })
          })
          this.deptTreeData = initData
          this.searchForm.deptId = rsp.data[0].deptId
          resolve()
        })
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      return new Promise((resolve) => {
        querySellerDown({ ...sellerData, deptId }).then(rsp => {
          this.sellers = rsp.data.map((v, i) => {
            if (!v.uiId) {
              v.name = '请选择'
              v.uiId = ''
            }
            return v
          })
          this.searchForm.sellerId = rsp.data[0].uiId
          resolve()
        })
      })
    },
    onDateChange (date, dataStr) {
      this.searchForm.startDate = dataStr[0]
      this.searchForm.endDate = dataStr[1]
    },
    exportExcel () {
      commonExport('/customer/exportCustomerPageList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    },
    async downLoadImg () {
      let _s = this
      // 滚轮滑动造成的，主要是html2canvas是根据body进行截图，若内容高度高于body时，就会出现这样的问题(大概意思就是有滚动条时造成的) 解决方案：(在生成截图前，先把滚动条置顶)
      window.pageYOffset = 0
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      let opts = {
        x: _s.$refs.imageWrapper.getBoundingClientRect().left + 0, // 绘制的dom元素相对于视口的位置，由于获取的位置比原本往前偏离的所以要加上，你需要根据自己的视图去计算
        y: _s.$refs.imageWrapper.getBoundingClientRect().top, // top没有偏离所以不用修改
        // backgroundColor: null, // 解决生成的图片有白边，只单单加和这个并没有效果
        width: _s.$refs.imageWrapper.offsetWidth - 0, // 因为多出的需要剪裁掉，
        height: _s.$refs.imageWrapper.offsetHeight,
        useCORS: true,
        scale: 3, // 因为生成图片会模糊，但是这个会使下载的图片变大，可以使用base64压缩
        dpi: window.devicePixelRatio // z
      }
      await html2canvas(_s.$refs.imageWrapper, opts).then(canvas => {
        let link = document.createElement('a')
        link.href = canvas.toDataURL() // 下载链接
        link.setAttribute('download', `二维码${Math.random()}.png`)
        link.style.display = 'none' // a标签隐藏
        document.body.appendChild(link)
        link.click()
      })
    },
    qrcode (id) {
      // eslint-disable-next-line no-unused-vars
      let qrcode = new QRCode('qrcode', {
        width: 200, // 二维码宽度，单位像素
        height: 200, // 二维码高度，单位像素
        text: `${TRUCKINGURL}/list?id=${id}`
      })
    }
  },
  mounted () {
    // 所属部门
    // 所属销售
    Promise.all([this.initDept(deptData), this.initSellerDown()]).then(result => {
      this.handleSubmit()
    })
  }
}
</script>

<style scoped>
.logo {
  width: 100%;
  text-align: center;
  overflow: hidden;
}
.logo img {
  width: 118px;
  margin-top: 30px;
}
.logo h1 {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  padding-bottom: 15px;
}

.c_code {
  text-align: center;
  width: 94%;
  margin: 0 3%;
  border-bottom: 1px dashed #ededed;
  border-top: 1px dashed #ededed;
  padding: 20px 0 5px 0;
}
.erw_hwgz {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}
.c_code h1 {
  margin-top: 210px;
  font-size: 14px;
  color: #333;
  font-weight: bold;
}
.c_code p {
  font-size: 12px;
  color: #999;
}

.c_people {
  width: 94%;
  margin: 0 3%;
  padding: 15px 0;
}
.c_people ul li {
  line-height: 22px;
  font-size: 14px;
  color: #333;
}
.c_people ul li img {
  width: 12px;
  float: left;
  margin-right: 5px;
  margin-top: 5px;
}
.c_people ul li span {
  color: #999;
}
</style>
